<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload2" @click="handleImport" v-hasPermi="['system:user:import']"
          size="small">导入专家</el-button>
        <el-button type="primary" plain icon="el-icon-s-custom" @click="checkNum" v-hasPermi="['system:user:import']"
          size="small">专家数量</el-button>
        <el-button type="primary" plain @click="onChangeClick" size="small">确定导入
        </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loadding" @selection-change="handleSelectionChange" :data="userList" row-key="id" ref="table2">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
      <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
      <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
    </el-table>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="设置专家数量" :visible.sync="open2" append-to-body width="400px">

      <el-row>
        <el-col :span="6">
          <span style="line-height:35px"> 分配专家数:</span>
        </el-col>
        <el-col :span="18">
          <el-input v-model="expertNum" placeholder="请输入专利上传人" maxlength="1" show-word-limit />
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="open2 = false">取 消</el-button>
        <el-button type="primary" @click="open2 = false">确 定</el-button>
      </span>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getGroupExpert" />
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { listExpert } from "@/api/system/expert/expert";
import { addGroupUsers, selectGroupUser } from "@/api/system/group/group";
export default {
  data () {
    return {
      loadding: true,
      groupId: null,
      isdisabled: false,
      proIds: [],
      userList: [],
      userIds: [],
      total: 0,
      open2: false,
      expertNum: 2,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        expert: 2,
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
    }
  },
  created () {
    this.getGroupExpert()
    this.groupId = JSON.parse(localStorage.getItem("groupId"))
    this.proIds = JSON.parse(localStorage.getItem("proIds"))
    this.getIsusers()
  },
  methods: {
    checkNum () {
      this.open2 = true
    },
    checkNumY () {
      this.open2 = false
    },
    getGroupExpert () {
      listExpert(this.queryParams).then((res) => {
        this.userList = res.rows;
        this.total = res.total;
        this.loadding = false;
        this.getIsusers()
      });
    },
    getIsusers () {
      const data = {
        id: this.groupId
      }
      selectGroupUser(data).then(res => {
        console.log(res)
        if (res.data.length != 0) {
          this.isdisabled = true
        }
        else {
          this.isdisabled = false
        }
      })
    },
    handleSelectionChange (selection) {
      // this.userIds = selection.map(item => item.userId)
      this.userIds = selection;
      if (this.userIds.length > this.expertNum) {
        this.userIds = this.userIds.slice(0, this.expertNum)
        this.userIds.forEach(row => {
          this.$refs.table2.toggleRowSelection(row, true);
        });
        selection = selection.slice(this.expertNum, selection.length)
        selection.forEach(row => {
          this.$refs.table2.toggleRowSelection(row, false);
        });
      }

    },
    /** 导入按钮操作 */
    handleImport () {
      this.upload.title = "专家导入";
      this.upload.open = true;
    },
    onChangeClick () {
      if (this.userIds.length > this.expertNum) {
        this.$message({
          message: '你最多只能选择' + this.expertNum + '个专家哦！',
          type: 'warning'
        });
      } else if (this.userIds.length < this.expertNum) {
        this.$message({
          message: '请选择' + this.expertNum + '个专家喔！',
          type: 'warning'
        });

      }
      else {
        this.userIds = this.userIds.map(item => item.userId);
        this.proIds = this.proIds.map(item => item.proId);
        console.log(this.userIds)
        console.log(this.proIds)
        console.log(this.groupId)
        const data = {
          userIds: this.userIds,
          proIds: this.proIds,
          id: this.groupId,
        }
        addGroupUsers(data).then(res => {
          if (res.code == 200) {
            this.$message({
              message: '添加成功',
              type: 'success'
            });
            this.getGroupExpert()
          }


        })
      }
    },
    /** 下载模板操作 */
    importTemplate () {
      this.download('system/user/importTemplate', {
      }, `expert_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    }
  }
}
</script>